<template>
    <div class="container">
        <el-form ref="formRef" :model="form" label-width="100px">
            <el-form-item label="页面标题" prop="title">
                <el-input v-model="form.title"></el-input>
            </el-form-item>
            <el-form-item label="页面类型" prop="path">
                <el-input v-model="form.type" disabled></el-input>
            </el-form-item>
            <el-form-item label="页面路径" prop="path">
                <el-input v-model="form.path"></el-input>
            </el-form-item>
            <el-form-item label="品牌" prop="des">
                <el-input v-model="form.brand" disabled></el-input>
            </el-form-item>
            <el-form-item label="发布日期" prop="date">
                <el-date-picker
                        type="datetime"
                        v-model="form.publishTime"
                        format="YYYY/MM/DD"
                        value-format="x"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="缩略图" prop="thumb">
                <el-upload
                        class="avatar-uploader"
                        :action="url"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                >
                    <img v-if="thumb" :src="thumb" class="avatar"/>
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus/>
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="车型" prop="model">
                <el-input style="width: 500px" v-model="pageContent.ref_model"></el-input>
            </el-form-item>
            <el-form-item label="MediaInfo">
                <el-table :data="pageContent.ref_article" border style="width: 100%">
                    <el-table-column align="center" label="引用文章" prop="title">
                        <template #default="scope">
                            <div style="display: flex; align-items: center">
                                <span style="margin-left: 10px">{{ scope.row.ref_article.title }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" width="800" label="简介" prop="title">
                        <template #default="scope">
                            <div style="display: flex; align-items: center">
                                <span style="margin-left: 10px">{{ scope.row.des }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column align="right">
                        <template #header>
                            <el-button
                                    type="warning"
                                    @click="
                  handleMediaInfo(-1, undefined)
                "
                            >添加
                            </el-button
                            >
                        </template>
                        <template #default="scope">
                            <el-button
                                    size="small"
                                    type="danger"
                                    @click="handleMediaInfo(scope.$index, scope.row)"
                            >修改
                            </el-button
                            >
                            <el-button
                                    size="small"
                                    type="danger"
                                    @click="deleteMediaInfo(scope.$index, scope.row)"
                            >删除
                            </el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <!--            <el-form-item label="主图" prop="mainImg">-->
            <!--                &lt;!&ndash;         <el-input style="width:500px" v-model="pageContent.ref_model"></el-input>&ndash;&gt;-->
            <!--                <img v-if="pageContent.main_img  && pageContent.main_img.resourceUrl != '' "-->
            <!--                     :src="pageContent.main_img.resourceUrl"-->
            <!--                     class="avatar" style="cursor: pointer" @click="visibleMainImgSelector = true"/>-->
            <!--                <el-icon v-else class="avatar-uploader-icon" @click="visibleMainImgSelector = true">-->
            <!--                    <Plus/>-->
            <!--                </el-icon>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="页面简介" prop="des">-->
            <!--                <el-input v-model="form.des"></el-input>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="引用文章" prop="article">-->
            <!--                <el-input-->
            <!--                        style="width: 400px"-->
            <!--                        v-model="pageContent.ref_article.title"-->
            <!--                        disabled-->
            <!--                ></el-input>-->
            <!--                <el-button-->
            <!--                        style="margin-left: 20px"-->
            <!--                        type="primary"-->
            <!--                        @click="articlePreView(pageContent.ref_article)"-->
            <!--                >预览-->
            <!--                </el-button-->
            <!--                >-->
            <!--                <el-button type="warning" @click="visible = true">选择</el-button>-->
            <!--            </el-form-item>-->
            <el-form-item label="参数主图" prop="mainImg">
                <!--         <el-input style="width:500px" v-model="pageContent.ref_model"></el-input>-->
                <img v-if="pageContent.feature.main_img.resourceUrl "
                     :src="pageContent.feature.main_img.resourceUrl"
                     class="avatar" style="cursor: pointer" @click="visibleFeatureImgSelector = true"/>
                <el-icon v-else class="avatar-uploader-icon" @click="visibleFeatureImgSelector = true">
                    <Plus/>
                </el-icon>
            </el-form-item>
            <el-form-item label="参数简介" prop="model">
                <el-input style="width: 500px" v-model="pageContent.feature.des"></el-input>
            </el-form-item>
            <el-form-item label="关键参数" prop="pageContent">
                <el-table :data="pageContent.feature.key" border style="width: 100%">
                    <el-table-column align="center" label="参数" prop="parameter"/>
                    <el-table-column align="center" label="数值" prop="value"/>
                    <el-table-column align="center" label="单位" prop="unit"/>
                    <el-table-column align="right">
                        <template #header>
                            <el-button type="warning" @click="visibleKeyEditor = true">添加</el-button>
                        </template>
                        <template #default="scope">
                            <el-button
                                    size="small"
                                    type="danger"
                                    @click="handleDeleteKey(scope.$index)"
                            >删除
                            </el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item label="引用图片" prop="image">
                <el-table :data="pageContent.ref_image" border style="width: 100%">
                    <el-table-column align="center" label="标题" prop="title"/>
                    <el-table-column align="right">
                        <template #header>
                            <el-button
                                    type="warning"
                                    @click="
                  visibleMediaSelector = true;
                  insertType = 1;
                "
                            >添加
                            </el-button
                            >
                        </template>
                        <template #default="scope">
                            <el-button
                                    size="small"
                                    type="danger"
                                    @click="handleImageDelete(scope.$index, scope.row)"
                            >删除
                            </el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item label="引用视频" prop="art">
                <el-input
                        style="width: 400px"
                        v-model="pageContent.ref_video.title"
                        disabled
                ></el-input>
                <el-button
                        style="margin-left: 20px"
                        type="warning"
                        @click="
            visibleMediaSelector = true;
            insertType = 2;
          "
                >选择
                </el-button
                >
            </el-form-item>
            <el-form-item label="车辆参数" prop="pageContent">
                <el-table :data="pageContent.model_info" border style="width: 100%">
                    <el-table-column align="center" label="参数" prop="parameter"/>
                    <el-table-column align="center" label="数值" prop="value"/>
                    <el-table-column align="right">
                        <template #header>
                            <el-button type="warning" @click="visibleEditor = true">添加</el-button>
                        </template>
                        <template #default="scope">
                            <el-button
                                    size="small"
                                    type="danger"
                                    @click="handleDelete(scope.$index)"
                            >删除
                            </el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item label="媒体联系人" prop="author">
                <el-input style="width: 500px;margin-right: 20px" v-model="pressContactName" disabled></el-input>
                <el-button type="warning" @click="visiblePressContact = true">选择</el-button>
                <el-button type="danger" @click="deletePressContact">清空</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="preView()">预览</el-button>
                <el-button type="primary" @click="saveEdit(formRef)">保 存</el-button>
                <el-button type="primary" v-if="form.isPublish == 0" @click="publish()"
                >发布
                </el-button
                >
                <el-button type="danger" v-if="form.isPublish != 0 " @click="unpublish()"
                >下架
                </el-button
                >

                <el-button type="warning" v-if="form.isPublish == 2" @click="publish()"
                >更新
                </el-button
                >
                <el-button type="primary" @click="router.go(-1)">返 回</el-button>
            </el-form-item>
        </el-form>
        <el-dialog
                v-model="visible"
                width="1000px"
                destroy-on-close
                :close-on-click-modal="false"
        >
            <ArticleSelector :update="updateArticle"></ArticleSelector>
        </el-dialog>

        <el-dialog
                v-model="visibleMainImgSelector"
                width="1300px"
                destroy-on-close
                :close-on-click-modal="false"
        >
            <imageSelector :update="updateMainImg"/>
        </el-dialog>
        <el-dialog
                v-model="visibleFeatureImgSelector"
                width="1300px"
                destroy-on-close
                :close-on-click-modal="false"
        >
            <imageSelector :update="updateFeatureImg"/>
        </el-dialog>
        <el-dialog
                v-model="visibleMediaSelector"
                width="1300px"
                destroy-on-close
                :close-on-click-modal="false"
        >
            <imageSelector v-if="insertType == 1" :update="updateMedia"/>
            <videoSelector v-if="insertType == 2" :update="updateMedia"/>
        </el-dialog>
        <el-dialog
                v-model="visibleEditor"
                width="500px"
                destroy-on-close
                :close-on-click-modal="false"
        >
            <ModelInfoEditor :update="updateModelInfo"></ModelInfoEditor>
        </el-dialog>

        <el-dialog
                v-model="visibleKeyEditor"
                width="500px"
                destroy-on-close
                :close-on-click-modal="false"
        >
            <ModelFeatureEditor :update="updateFeatureKey"></ModelFeatureEditor>
        </el-dialog>

        <el-dialog
                v-model="visiblePressContact"
                width="1000px"
                destroy-on-close
                :close-on-click-modal="false"
                @close="closeDialog"
        >
            <PresscontactSelector :update="updatePressContact"></PresscontactSelector>
        </el-dialog>

        <el-dialog
                v-model="visibleMediaInfoEditor"
                width="1000px"
                destroy-on-close
                :close-on-click-modal="false"
                @close="closeDialog"
        >
            <ModelMediaInfoEditor :data="mediaInfoItem" :index="mediaInfoIndex"
                                  :update="updateMediaInfo"></ModelMediaInfoEditor>
        </el-dialog>
    </div>

</template>

<script setup lang="ts">
    import {
        ElMessage,
        ElMessageBox,
        FormInstance,
        FormRules,
        UploadProps
    } from "element-plus";
    import {onBeforeUnmount, ref, reactive, shallowRef, onMounted} from "vue";
    import {useRoute, useRouter} from "vue-router";
    import ArticleSelector from "../../components/article-selector.vue";
    import PDFSelector from "../../components/pdf-selector.vue";
    import imageSelector from "../../components/image-selector.vue";
    import videoSelector from "../../components/video-selector.vue";
    import ModelInfoEditor from "../../components/model-info-table-edit.vue";
    import ModelFeatureEditor from "../../components/model-feature-table-edit.vue";
    import ModelMediaInfoEditor from "../../components/model-mediainfo-table-edit.vue";

    import Editor from "../../components/editor.vue";
    // 引入vue-json-editor模块
    import base from "../../utils/base";
    import page from "../../api/page";

    //首先在setup中定义
    const route = useRoute();
    const router = useRouter();

    // 推荐新闻列表
    const newsTable = ref([]);

    // 媒体素材选择
    const visibleMediaSelector = ref(false);
    const insertType = ref(1);

    const visible = ref(false);
    const visibleEditor = ref(false);
    const visibleKeyEditor = ref(false);
    const visibleMainImgSelector = ref(false);
    const visibleFeatureImgSelector = ref(false);
    const visibleMediaInfoEditor = ref(false);

    // 媒体联系人
    const pressContactName = ref("");


    // const url = `${base.rq}/file/upload`;
    const url = `${base.rq}/file/upload?token=${localStorage.getItem("token")}`

    const props = defineProps({
        data: {
            type: Object,
            required: true,
        },
        edit: {
            type: Boolean,
            required: false,
        },
        update: {
            type: Function,
            required: true,
        },
    });

    const defaultData = {
        id: "",
        title: "",
        modName: "",
        path: "",
        des: "",
        isArticle: 1,
        thumbnailUrl: "",
        pageContent: "",
        isPublish: 0,
        publishTime: "",
        articleType: "",

    };

    const form = ref({...(props.edit ? props.data : defaultData)});
    const thumb = props.edit ? ref(props.data.thumbnailUrl) : ref("");

    interface Page {
        main_img: {
            resourceUrl: string
        },
        ref_model: string,
        ref_article: [],
        ref_image: string[],
        ref_video: object,
        model_info: string[],
        feature: {
            des: string,
            configuration_des: string,
            main_img: {
                resourceUrl: string
            },
            key: string[],
        }
    }

    const feature = ref({
        des: "",
        configuration_des: "",
        main_img: {
            resourceUrl: ""
        },
        key: [],
    })
    const pageContent = ref<Page>({
        main_img: {
            resourceUrl: ''
        },
        ref_model: '',
        ref_article: [],
        ref_image: [],
        ref_video: {},
        model_info: [],
        feature: {
            des: "",
            configuration_des: "",
            main_img: {
                resourceUrl: ""
            },
            key: [],
        }
    });

    // const mediaList = ref([]);

    // 获取草稿内容
    const getData = () => {
        page.getSketchById({id: route.query.id}, (res) => {
            if (res.code === 200) {
                form.value = res.data;
                form.value.publishTime = Number(form.value.publishTime);
                thumb.value = res.data.thumbnailUrl;
                console.log(res.data)
                if (res.data.pageContent) {
                    pageContent.value = res.data.pageContent;
                    if (!pageContent.value.feature) {
                        console.log("feature")
                        pageContent.value.feature = feature.value;
                    }
                    if (!(pageContent.value.ref_article instanceof Array)) {
                        pageContent.value.ref_article = [];
                    }
                    // if (pageContent.value.pressContact) {
                    //     pressContactName.value = pageContent.value.pressContact.name;
                    // }
                    // insertContent(form.value.pageContent);
                    // console.log(pageContent.value)
                }
            }
        });
    };
    getData();

    const formRef = ref<FormInstance>();
    const saveEdit = (formEl: FormInstance | undefined) => {
        commit();
        console.log(form.value);
    };

    // json 保存
    const commit = () => {
        // console.log(valueHtml)
        // pageContent.value["publishTime"] =
        form.value.pageContent = pageContent.value;
        if (form.value.isPublish === 1) {
            form.value.isPublish = 2;
        }
        page.save(form.value, (res) => {
            if (res.code === 200) {
                console.log(res);
                ElMessage.success("保存成功！");
                props.update();
                getData();
            } else {
                ElMessage.success("保存失败！");
                props.update();
            }
        });
    };

    // json 发布
    const publish = () => {
        form.value.pageContent = pageContent.value;
        page.publish(form.value, (res) => {
            if (res.code === 200) {
                console.log(res);
                ElMessage.success("发布成功！");
                getData();
                props.update();
            } else {
                ElMessage.success("发布失败！");
                getData();
                props.update();
            }
        });
    };

    // json 下架
    const unpublish = () => {
        form.value.pageContent = pageContent.value;
        page.unpublish(form.value, (res) => {
            if (res.code === 200) {
                console.log(res);
                ElMessage.success("下架成功！");
                getData();
                props.update();
            } else {
                ElMessage.success("下架失败！");
                getData();
                props.update();
            }
        });
    };

    const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
        // form.value.thumb = URL.createObjectURL(uploadFile.raw!);
        form.value.thumbnailUrl = response.data.realName;
        thumb.value = response.data.tmpUrl;
    };

    // 选择下载PDF
    // const visiblePdf = ref(false);
    // const updatePdf = (item) => {
    //   docTitle.value = item.title;
    //   pageContent.value.doc = item;
    // };
    //////////////////////////////////////////////

    // 添加媒体素材
    const updateMedia = (item) => {
        if (insertType.value == 1) {
            pageContent.value.ref_image.push(item);
        }
        if (insertType.value == 2) {
            pageContent.value.ref_video = item;
        }
        visibleMediaSelector.value = false;
    };

    const updateArticle = (item) => {
        // newsTable.value.push(item);
        pageContent.value.ref_article = item;
        visible.value = false;
    };

    const updateModelInfo = (content) => {
        pageContent.value.model_info.push(content);
        visibleEditor.value = false;
    };
    const updateFeatureKey = (content) => {
        pageContent.value.feature.key.push(content);
        visibleKeyEditor.value = false;
    };

    const updateMainImg = (content) => {
        console.log(content)
        pageContent.value.main_img = content;
        visibleMainImgSelector.value = false;

    }
    const updateFeatureImg = (content) => {
        console.log(content)
        pageContent.value.feature.main_img = content;
        visibleFeatureImgSelector.value = false;
    }

    // 删除操作
    const handleImageDelete = (index: number) => {
        // 二次确认删除
        ElMessageBox.confirm("确定要删除吗？", "提示", {
            type: "warning",
        })
            .then(() => {
                ElMessage.success("删除成功");
                pageContent.value.ref_image.splice(index, 1);
            })
            .catch(() => {
            });
    };

    const handleDelete = (index: number) => {
        // 二次确认删除
        ElMessageBox.confirm("确定要删除吗？", "提示", {
            type: "warning",
        })
            .then(() => {
                ElMessage.success("删除成功");
                pageContent.value.model_info.splice(index, 1);
            })
            .catch(() => {
            });
    };

    const handleDeleteKey = (index: number) => {
        // 二次确认删除
        ElMessageBox.confirm("确定要删除吗？", "提示", {
            type: "warning",
        })
            .then(() => {
                ElMessage.success("删除成功");
                pageContent.value.feature.key.splice(index, 1);
            })
            .catch(() => {
            });
    };

    const articlePreView = (item) => {
        window.open(`${base.newsroom}/article/${item.id}?token=${localStorage.getItem("token")}`, "_blank");
    };

    const preView = () => {
        window.open(`${base.newsroom}/${form.value.path}${form.value.id}?token=${localStorage.getItem("token")}`, "_blank");
    };

    //媒体联系人选择
    const visiblePressContact = ref(false);
    const closeDialog = () => {
        visiblePressContact.value = false;
    };
    const updatePressContact = (item) => {
        pressContactName.value = item.name;
        pageContent.value.pressContact = item;
        visiblePressContact.value = false;
    };
    const deletePressContact = () => {
        pressContactName.value = "";
        delete pageContent.value.pressContact;
    }

    //添加MeidaInfo
    const mediaInfoIndex = ref(-1);
    const mediaInfoItem = ref();
    const handleMediaInfo = (index, item) => {
        console.log(index, item)
        mediaInfoIndex.value = index;
        mediaInfoItem.value = item;
        visibleMediaInfoEditor.value = true;
    }
    const deleteMediaInfo = (index, item) => {
        ElMessageBox.confirm("确定要删除吗？", "提示", {
            type: "warning",
        })
            .then(() => {
                ElMessage.success("删除成功");
                pageContent.value.ref_article.splice(index, 1);
            })
            .catch(() => {
            });
    }
    const updateMediaInfo = (item, index) => {
        console.log(item, index)
        if (index == -1) {
            pageContent.value.ref_article.push(item);
        } else {
            pageContent.value.ref_article[index] = item;
        }
        visibleMediaInfoEditor.value = false;
    }
</script>
<style>
    .container {
        max-width: 1600px;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }

    .editor-container {
        width: 1000px;
    }

    .editor {
        padding: 0px;
    }

    .editor :deep(.jsoneditor-poweredBy) {
        display: none;
    }

    .avatar {
        width: 300px;
    }
</style>
